package com.live.task;

import java.io.File;
import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.live.activity.R;
import com.live.common.Constant;
import com.live.common.LiveImageHelper;
import com.live.entity.User;

public class LiveUser extends AsyncTask<User, Integer, String> {

	private SharedPreferences userInfo = null;

	private ProgressDialog proDialog = null;

	private Context context = null;

	public String typeName = null;

	public String url = null;

	public Activity dialog = null;

	public User user = null;

	public LiveUser(Context context, String url, String typeName, Activity dialog) {
		this.url = url;
		this.context = context;
		this.typeName = typeName;
		this.dialog = dialog;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
		proDialog = new ProgressDialog(context);
		proDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		proDialog.setMessage("正在" + typeName + "，请稍候...");
		proDialog.show();
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(User... params) {
		String result = null;
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		user = params[0];
		FileEntity entity = null;

		// 头像未更新时，不提交头像
		if (user.getUserPicBitmap() != null) {
			entity = new FileEntity(new File(Constant.ALBUM_PATH + "tmp.jpg"), "binary/octet-stream");
		}

		userInfo = context.getSharedPreferences(Constant.PREFS_NAME, 0);
		SharedPreferences.Editor editor = userInfo.edit();
		editor.putString("userId", user.getUserId());

		if ("注册".equals(typeName)) {
			result = userRegist(url);
		} else if ("登录".equals(typeName)) {
			result = userLogin(url);
			if (Constant.SUCCESS.equals(result)) {
				// 如果用户上传过头像
				if (Constant.Y.equals(user.getUserPic())) {
					// 从远程服务器重新更新头像
					LiveImageHelper.buildBitMap(Constant.SITE_URL + Constant.SITE_AVATAR_PATH, user.getId());
					editor.putString("userPic", Constant.Y);
				}
			}
		} else if ("编辑".equals(typeName)) {
			result = userEdit(url, entity);
			if (Constant.SUCCESS.equals(result)) {
				// 头像未提交时，不更新头像
				if (user.getUserPicBitmap() != null) {

					// 保存头像到本软件目录
					try {
						LiveImageHelper.saveImage(user.getUserPicBitmap(), user.getId());
					} catch (IOException e) {
						e.printStackTrace();
					}
					editor.putString("userPic", Constant.Y);
				}
			}
		}

		editor.putString("userSex", user.getUserSex());
		editor.putString("userType", user.getUserType());
		editor.putString("userBirthday", user.getUserBirthday());

		if (Constant.SUCCESS.equals(result)) {
			editor.commit();
		}
		return result;

	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {

		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		proDialog.dismiss();

		if (result.startsWith(Constant.SUCCESS)) {
			// 提示修改成功
			Toast.makeText(context, "用户" + typeName + "成功！", Toast.LENGTH_LONG).show();

			// 关闭输入法键盘
			// InputMethodManager m = (InputMethodManager)
			// context.getSystemService(Context.INPUT_METHOD_SERVICE);
			// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

			// 关闭对话框
			dialog.finish();
		} else {
			// 提示修改失败
			Toast.makeText(context, result, Toast.LENGTH_LONG).show();
		}
	}

	// 用户编辑
	public String userEdit(String url, FileEntity entry) {
		String result = context.getString(R.string.net_error);
		HttpClient client = new DefaultHttpClient();
		try {
			// 提拱默认的HttpClient实现
			HttpPost request = new HttpPost(new URI(url));
			request.setEntity(entry);
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						result = new JSONObject(out).getString("results");
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 用户注册
	public String userRegist(String url) {
		String result = context.getString(R.string.net_error);
		HttpClient client = new DefaultHttpClient();
		HttpPost request;
		try {
			// 提拱默认的HttpClient实现
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						result = new JSONObject(out).getString("results");

						// 设置用户ID
						String id = new JSONObject(out).getString("id");
						userInfo = context.getSharedPreferences(Constant.PREFS_NAME, 0);
						SharedPreferences.Editor editor = userInfo.edit();
						editor.putString("id", id);
						editor.commit();

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 用户登录
	public String userLogin(String url) {
		String result = context.getString(R.string.net_error);
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						boolean error = new JSONObject(out).getBoolean("error");
						if (!error) {
							JSONArray userArray = new JSONObject(out).getJSONArray("results");

							user.setId(userArray.getJSONObject(0).getString("id"));
							user.setUserId(userArray.getJSONObject(0).getString("userId"));
							user.setUserPic(userArray.getJSONObject(0).getString("userPic"));
							user.setUserSex(userArray.getJSONObject(0).getString("userSex"));
							user.setUserBirthday(userArray.getJSONObject(0).getString("userBirthday"));
							user.setUserType(userArray.getJSONObject(0).getString("userType"));

							userInfo = context.getSharedPreferences(Constant.PREFS_NAME, 0);
							SharedPreferences.Editor editor = userInfo.edit();
							editor.putString("id", user.getId());
							editor.commit();

							return Constant.SUCCESS;
						} else {
							result = new JSONObject(out).getString("results");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}